package com.yingpai.fitness.dvp_2_0.main.util;

import android.os.CountDownTimer;
import android.widget.TextView;

/**
 * Created by Administrator on 2018/5/8.
 * <p>
 * 继承官方 CountDownTimer 实现倒计时功能
 */

public class XCountDownTimer extends CountDownTimer {

    private TextView textView;

    private OnCountDownNumListener listener;
    /**
     * 定义一个flag
     * 如果时欢迎界面倒计时 flag 为0，注册  修改密码倒计时 为1
     */
    private int flag;


    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public XCountDownTimer(long millisInFuture, long countDownInterval, TextView textView, int flag) {
        super(millisInFuture, countDownInterval);
        this.textView = textView;
        this.flag = flag;
    }

    /**
     * 最简单的倒计时类，实现了官方的CountDownTimer类（没有特殊要求的话可以使用）
     * 即使退出activity，倒计时还能进行，因为是创建了后台的线程。需要在必要的时候取消
     * 有onTick，onFinsh、cancel和start方法
     */
    @Override
    public void onTick(long millisUntilFinished) {
        switch (flag) {

            case 0:
                textView.setText(millisUntilFinished / 1000 + " | 跳过");

                break;
            case 1:
                //每隔countDownInterval秒会回调一次onTick()方法
                textView.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
                textView.setEnabled(false);
                break;
        }
    }

    @Override
    public void onFinish() {

//针对注册  找回密码 / 绑定手机号
        if (flag != 0) {
            textView.setText("获取验证码");
            textView.setEnabled(true);
        } else {

            textView.setText("0 | 跳过");
            if (listener != null) {
                listener.setCountDownNum(0);
            }
        }
    }

    public interface OnCountDownNumListener {

        /**
         * @param num 数字
         */
        void setCountDownNum(int num);
    }

    public void setListener(OnCountDownNumListener listener) {
        this.listener = listener;
    }
}
